from redis.sentinel import Sentinel
import redis,logging,base64
import  configparser as cp

class RedisClient:
    def __init__(self,redis_master_name,redis_hosts,redis_passwd,redis_db=0,redis_socket_timeout=3):
        self.redis_master_name=redis_master_name
        host_part = redis_hosts.split(",")
        assert len(host_part)>0
        self.redis_hosts=[]
        print(type(self.redis_hosts))
        for i in range(len(host_part)):
            ip_port=host_part[i].split(':')
            if len(ip_port)<2:
                raise Exception("redis_hosts 格式错误")
            self.redis_hosts.append((str(ip_port[0]),int(ip_port[1])))
        # self.redis_passwd=base64.b64decode(redis_passwd).decode()
        self.redis_passwd=redis_passwd
        self.redis_db=redis_db
        self.redis_soket_timeout=redis_socket_timeout
        self.redis_server=Sentinel(self.redis_hosts,socket_timeout=redis_socket_timeout)

    '''
    获取sentinel集群的master实例
   得到redis_server对象
    '''
    def master(self):
        if self.redis_server is None:
            raise Exception("Redis server is not initialized!")
        return self.redis_server.master_for(self.redis_master_name,socket_timeout=self.redis_soket_timeout,passwd=self.redis_passwd,db=self.redis_db)

    """
    hget操作
    """
    def hget_redis_data(self,index,key):
        value=None

        try:
            value=self.master().hget(index,key)
        except redis.exceptions.ConnectionError as err:
            logging.error(err)
        except Exception as err:
            logging.error(err)

        try:
            value=value.decode()
        except:
            pass

        return value
    """
    hset操作
    """
    def hset_redis_data(self,index,key,value):
        ret=True
        try:
            ret=self.master().hset(index,key,value)

        except redis.exceptions.ConnectionError as err:
            logging.error(err)
            ret=False
        except Exception as err:
            logging.error(err)
            ret=False
        return ret
    """
    hsetex操作
    """
    def hsetex_redis_data(self,index,key,value,time=24*3600):
        ret=True
        try:
            ret=self.master().hset(index,key,value)
            if ret is False:
                raise Exception("hset key(%s,%s) failed."%(str(index),str(key)))
            ret=self.expire(index,time)

        except redis.exceptions.ConnectionError as err:
            logging.error(err)
            ret=False
        except Exception as err:
            logging.error(err)
            ret=False

        return ret

    """
    get操作
    """
    def get_redis_data(self,key):
        value=None
        try:
            value=self.master().get(key)
        except redis.exceptions.ConnectionError as err:
            logging.error(err)
        except Exception as err:
            logging.error(err)

        try:
            value=value.decode()
        except:
            pass
        return value
    """
    set操作
    """
    def set_redis_data(self,key,value):
        ret=True
        try:
            ret=self.master().set(key,value)

        except redis.exceptions.ConnectionError as err:
            logging.error(err)
            ret=False
        except Exception as err:
            logging.error(err)
            ret=False
        return ret

    """
        setex操作
    """

    def setex_redis_data(self,  key, value, time=24 * 3600):
        ret = True
        try:
            ret = self.master().setex(key,time,value)

        except redis.exceptions.ConnectionError as err:
            logging.error(err)
            ret = False
        except Exception as err:
            logging.error(err)
            ret = False

        return ret

    """
    设置key的生存周期
    """
    def expire(self,name,time=24*3600):
        ret=True
        try:
            ret=self.master().expire(name,time)
        except redis.exceptions.ConnectionError as err:
            logging.error(err)
            ret = False
        except Exception as err:
            logging.error(err)
            ret = False

        return ret

if __name__ == '__main__':
    conf=cp.ConfigParser()
    conf.read("D:\PythonProject\model-onlineframe-pythonmo\model.ini",encoding='utf-8')
    rc=RedisClient(redis_hosts=conf.get('server','redis_hosts'),redis_master_name=conf.get('server','redis_master_name'),redis_passwd=conf.get('server','redis_passwd')).master()
    # rc.set_redis_data('a','333')
    # rc.get_redis_data('a')
    rc.set("abc",'sss')